package in.muton.edushare.panels.upload.uploadify;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.util.upload.FileItem;
import org.apache.wicket.util.upload.FileUploadException;

public abstract class UploadifyProcessPage extends WebPage {
	
	private Log log = LogFactory.getLog(UploadifyProcessPage.class);
	private Map<String, String[]> paramMap;
	
	@SuppressWarnings("unchecked")
	public UploadifyProcessPage(PageParameters params){
		
		try {
			HttpServletRequest req = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
			MultipartServletWebRequest multipartReq = new MultipartServletWebRequest(req, Bytes.MAX);
			paramMap = (Map<String, String[]>)multipartReq.getParameterMap();
			
			log.debug("Uploadify Process Page. Multipart request created");
			for(FileItem fileItem: multipartReq.getFiles().values()){
				log.debug("File Item: " + fileItem.getName());
				processFile(fileItem);
				log.debug("File Item Delete: " + fileItem.getName());
				fileItem.delete();
			}
		} catch (FileUploadException e) {
			log.fatal("Error while uploading file with Uploadify", e);
		}
	}
	
	public abstract void processFile(FileItem fileItem);

	public Map<String, String[]> getParamMap() {
		return paramMap;
	}
	
	public String[] getParam(String paramKey){
		return paramMap.get(paramKey);
	}
}
